package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.guli.service.oss.service.impl.FileServiceImpl;
import com.wjl.guli.common.base.ExceptionUtils;
import com.wjl.guli.common.base.R;
import com.wjl.guli.common.base.ResultCodeEnum;
import com.wjl.guli.common.base.exception.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
@Slf4j
@Api(tags="阿里云文件管理")
@CrossOrigin
@RequestMapping("/admin/oss/file")
@RestController
public class FileController {
    @Autowired
    FileServiceImpl fileService;

    @ApiOperation("文件上传")
    @PostMapping(value="upload")
    public R upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module){
        InputStream inputStream = null;
        String uploadUrl= null;
        try {
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            uploadUrl = fileService.upload(inputStream, module, originalFilename);
            //返回r对象
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    @ApiOperation(value = "删除用户头像")
    @DeleteMapping("removeAvatar")
    public R removeAvatar(@ApiParam(value = "图片地址",required = true) @RequestBody String url) {
        fileService.removeAvatar(url);
        return R.ok().message("删除成功");
    }
    @ApiOperation(value = "测试")
    @GetMapping("test")
    public R test() {
        log.info("oss test被调用");
        return R.ok();
    }


}
